package spoc.interfaces;

import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import spoc.classes.BancoDeDados;
import spoc.classes.Cliente;
import spoc.classes.Pedido;
import spoc.classes.Cortina;


/**
 *
 * @author arthur
 */
public class JanelaPedido extends Janela {

    private JanelaAdicionaCortina adicionaCortina;
    private JanelaAdicionaCliente adicionaCliente;
    private TipoJanela tipo;
    private DecimalFormat formatoDecimal;
    private double total;
    private Cliente cliente;
    private JTable tabelaCortinas;
    private JTable tabelaServicos;
    private double[] porcentagemTamanhoColunas;
    private Pedido pedido;

    /** Creates new form JanelaVenda */
    public JanelaPedido(TipoJanela tipo, Pedido p) {
        this.tipo = tipo;
        initComponents();

        if(p == null){
            pedido = new Pedido();
        } else {
            pedido = p;
        }

        
        adicionaCortina = new JanelaAdicionaCortina(this);
        adicionaCliente = new JanelaAdicionaCliente(this);

        this.setLocationRelativeTo(this.getContentPane());

        total = 0.0;
        formatoDecimal = new DecimalFormat("0.00");

        scrollItens.setPreferredSize(new java.awt.Dimension(480, 200));

        tabelaCortinas = new JTable();
        tabelaServicos = new JTable();

        tabelaCortinas.setMaximumSize(new java.awt.Dimension(300, 100));
        tabelaServicos.setMaximumSize(new java.awt.Dimension(300, 100));
        scrollItens.setViewportView(tabelaCortinas);

        ListSelectionModel modeloSelecaoProdutos = tabelaCortinas.getSelectionModel();
        ListSelectionModel modeloSelecaoServicos = tabelaServicos.getSelectionModel();
        modeloSelecaoProdutos.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        modeloSelecaoServicos.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        setModelo(tabelaCortinas,
                new String[]{"Código", "Nome", "Qtde", "Preço"},
                new double[]{15, 50, 15, 20});

        setModelo(tabelaServicos,
                new String[]{"Código", "Nome", "Animal", "Preço"},
                new double[]{15, 40, 25, 19.5});

        modeloSelecaoProdutos.addListSelectionListener(new ListSelectionListener() {

            public void valueChanged(ListSelectionEvent e) {
                verificarBotaoRemover(tabelaCortinas);
            }
        });
        modeloSelecaoServicos.addListSelectionListener(new ListSelectionListener() {

            public void valueChanged(ListSelectionEvent e) {
                verificarBotaoRemover(tabelaServicos);
            }
        });

        if(this.tipo == TipoJanela.INFORMACAO){
            desabilitarCampos();
            preencher();
        } else {
            reiniciar();
        }
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        botaoPesquisarCliente = new javax.swing.JButton();
        labelCliente = new javax.swing.JLabel();
        campoCodigo = new javax.swing.JTextField();
        botaoPesquisaItem = new javax.swing.JButton();
        botaoAdd = new javax.swing.JButton();
        scrollItens = new javax.swing.JScrollPane();
        botaoRemover = new javax.swing.JButton();
        labelTotal = new javax.swing.JLabel();
        botaoCancelar = new javax.swing.JButton();
        botaoCadastra = new javax.swing.JButton();
        campoTamanho = new javax.swing.JTextField();
        labelCodigo = new javax.swing.JLabel();
        labelTamanho = new javax.swing.JLabel();
        labelCortina = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Nova Venda");
        setMinimumSize(new java.awt.Dimension(570, 370));
        setResizable(false);
        getContentPane().setLayout(new java.awt.GridBagLayout());

        botaoPesquisarCliente.setText("Pesquisar");
        botaoPesquisarCliente.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                botaoPesquisarClienteMouseClicked(evt);
            }
        });
        botaoPesquisarCliente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoPesquisarClienteActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        getContentPane().add(botaoPesquisarCliente, gridBagConstraints);

        labelCliente.setText("CLIENTE");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridwidth = 6;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        getContentPane().add(labelCliente, gridBagConstraints);

        campoCodigo.setMinimumSize(new java.awt.Dimension(90, 24));
        campoCodigo.setPreferredSize(new java.awt.Dimension(90, 24));
        campoCodigo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mudarCampo(evt);
            }
        });
        campoCodigo.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                digitarCampo(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.insets = new java.awt.Insets(5, 0, 5, 0);
        getContentPane().add(campoCodigo, gridBagConstraints);

        botaoPesquisaItem.setText("P");
        botaoPesquisaItem.setPreferredSize(new java.awt.Dimension(26, 26));
        botaoPesquisaItem.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                botaoPesquisaItemMouseClicked(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 3;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(5, 0, 5, 5);
        getContentPane().add(botaoPesquisaItem, gridBagConstraints);

        botaoAdd.setText("Adicionar");
        botaoAdd.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                clicarBotaoAdicionar(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 6;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.ipadx = 15;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        getContentPane().add(botaoAdd, gridBagConstraints);

        scrollItens.setMinimumSize(new java.awt.Dimension(500, 200));
        scrollItens.setPreferredSize(new java.awt.Dimension(500, 200));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.gridwidth = 7;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 5);
        getContentPane().add(scrollItens, gridBagConstraints);

        botaoRemover.setText("Remover");
        botaoRemover.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                clicarRemover(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.ipadx = 40;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(0, 5, 5, 5);
        getContentPane().add(botaoRemover, gridBagConstraints);

        labelTotal.setFont(new java.awt.Font("Ubuntu", 0, 18));
        labelTotal.setForeground(new java.awt.Color(225, 1, 1));
        labelTotal.setText("Total 00.00");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 3;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.gridwidth = 4;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(0, 5, 5, 5);
        getContentPane().add(labelTotal, gridBagConstraints);

        botaoCancelar.setText("Cancelar");
        botaoCancelar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                cancelar(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 4;
        gridBagConstraints.ipadx = 40;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        getContentPane().add(botaoCancelar, gridBagConstraints);

        botaoCadastra.setText("Pagar");
        botaoCadastra.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                pagar(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 6;
        gridBagConstraints.gridy = 4;
        gridBagConstraints.ipadx = 40;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        getContentPane().add(botaoCadastra, gridBagConstraints);

        campoTamanho.setMinimumSize(new java.awt.Dimension(50, 24));
        campoTamanho.setPreferredSize(new java.awt.Dimension(50, 24));
        campoTamanho.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mudarCampo(evt);
            }
        });
        campoTamanho.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                digitarCampo(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 5;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        getContentPane().add(campoTamanho, gridBagConstraints);

        labelCodigo.setText("Código");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        getContentPane().add(labelCodigo, gridBagConstraints);

        labelTamanho.setText("Metros");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 4;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        getContentPane().add(labelTamanho, gridBagConstraints);

        labelCortina.setFont(new java.awt.Font("Ubuntu", 1, 18)); // NOI18N
        labelCortina.setText("Cortina:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        getContentPane().add(labelCortina, gridBagConstraints);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void botaoPesquisarClienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoPesquisarClienteActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_botaoPesquisarClienteActionPerformed

    private void botaoPesquisaItemMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_botaoPesquisaItemMouseClicked
        if(botaoPesquisaItem.isEnabled()){
            JanelaAdiciona adiciona;

            
            adiciona = adicionaCortina;
           


            adiciona.setModalityType(java.awt.Dialog.DEFAULT_MODALITY_TYPE);
            adiciona.setModal(true);
            adiciona.setVisible(true);
        }
    }//GEN-LAST:event_botaoPesquisaItemMouseClicked

    private void botaoPesquisarClienteMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_botaoPesquisarClienteMouseClicked
        if(botaoPesquisarCliente.isEnabled()){
            adicionaCliente.setModalityType(java.awt.Dialog.DEFAULT_MODALITY_TYPE);
            adicionaCliente.setModal(true);
            adicionaCliente.setVisible(true);
        }
    }//GEN-LAST:event_botaoPesquisarClienteMouseClicked

    private void pagar(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_pagar
        if(botaoCadastra.isEnabled() && !existemDependencias()){
            
        }
    }//GEN-LAST:event_pagar

    private void cancelar(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cancelar
        cancelar();
    }//GEN-LAST:event_cancelar

    private void mudarCampo(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mudarCampo
        if(!campoTamanho.getText().equals("")
                || !campoCodigo.getText().equals("")){
            botaoAdd.setVisible(true);
        } else {
            botaoAdd.setVisible(false);
        }
    }//GEN-LAST:event_mudarCampo

    private void digitarCampo(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_digitarCampo
        if((campoTamanho.getText().equals("")
                    || campoTamanho.getText().equals(""))
                    || ((campoCodigo.getText().equals("")
                    || campoCodigo.getText().equals("")))){
                botaoAdd.setVisible(false);
            } else {
                botaoAdd.setVisible(true);
            }
    }//GEN-LAST:event_digitarCampo

    private void clicarBotaoAdicionar(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_clicarBotaoAdicionar
        if(botaoAdd.isVisible()){
            
            Cortina cortina;
                try {
                    cortina = BancoDeDados.consultar(new Cortina(Integer.valueOf(campoCodigo.getText())))[0];
                } catch(ArrayIndexOutOfBoundsException e){
                    JOptionPane.showMessageDialog(this, "Este Cortina não existe!");
                    return;
                }

                int tamanho = Integer.valueOf(campoTamanho.getText());

                
                Object[] dados = new Object[4];
                dados[0] = cortina.getCodigo();
                dados[1] = cortina.getNome();
                dados[2] = tamanho;
                dados[3] = formatoDecimal.format(cortina.getValor());

                setTotal((cortina.getValor()) + total);

                DefaultTableModel model = (DefaultTableModel) this.tabelaCortinas.getModel();

                boolean existeProduto = false;
                for(int i = 0; i < model.getRowCount(); i++){
                    int codigo = (Integer) model.getValueAt(i, 0);
                    if(codigo == cortina.getCodigo()){
                        int q = (Integer) model.getValueAt(i, 2);
                        model.setValueAt(q + tamanho, i, 2);
                        pedido.getCarrinhoCortinas().getQtde().set(i, pedido.getCarrinhoCortinas().getQtde().get(i) + tamanho);
                        existeProduto = true;
                        }
                        
                    }
            
            botaoAdd.setEnabled(false);
            campoCodigo.setText("");
            campoTamanho.setText("");
            
        }
    }//GEN-LAST:event_clicarBotaoAdicionar

    private void clicarRemover(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_clicarRemover
        if(botaoRemover.isVisible()){
            JTable tabela;
            
            tabela = tabelaCortinas;

            DefaultTableModel model = (DefaultTableModel) tabela.getModel();

            String preco = (String) tabela.getValueAt(tabela.getSelectedRow(), 3);
            String qtde = (String) tabela.getValueAt(tabela.getSelectedRow(), 2);
            setTotal(total - (Double.valueOf(preco) * Integer.valueOf(qtde)));

            int codigo = (Integer) tabela.getValueAt(tabela.getSelectedRow(), 0);

            
            pedido.getCarrinhoCortinas().remove(codigo);
            

            model.removeRow(tabela.getSelectedRow());
        }
    }//GEN-LAST:event_clicarRemover

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new JanelaPedido(TipoJanela.CADASTRO, null).setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton botaoAdd;
    private javax.swing.JButton botaoCadastra;
    private javax.swing.JButton botaoCancelar;
    private javax.swing.JButton botaoPesquisaItem;
    private javax.swing.JButton botaoPesquisarCliente;
    private javax.swing.JButton botaoRemover;
    private javax.swing.JTextField campoCodigo;
    private javax.swing.JTextField campoTamanho;
    private javax.swing.JLabel labelCliente;
    private javax.swing.JLabel labelCodigo;
    private javax.swing.JLabel labelCortina;
    private javax.swing.JLabel labelTamanho;
    private javax.swing.JLabel labelTotal;
    private javax.swing.JScrollPane scrollItens;
    // End of variables declaration//GEN-END:variables

    /**
     * Configura o label de total na janela. 
     * @param valor O valor do total de compras
     */
    public void setTotal(double valor) {
        total = valor;
        labelTotal.setText("Total R$ " + formatoDecimal.format(valor));
    }

    protected final void reiniciar() {

        labelCliente.setText("CLIENTE");
        campoCodigo.setText("");
        campoTamanho.setText("");
        labelTamanho.setText("Qtde");
        

        //remove todos os elementos das tabelas de serviços e produtos.
        ((DefaultTableModel) tabelaCortinas.getModel()).getDataVector().removeAllElements();
        ((DefaultTableModel) tabelaServicos.getModel()).getDataVector().removeAllElements();

        setTotal(0.0);
        botaoAdd.setVisible(false);
        botaoRemover.setVisible(false);

        desabilitarCampos();

        tabelaCortinas.updateUI();
        tabelaServicos.updateUI();
    }

    protected final void desabilitarCampos() {
        if(tipo == TipoJanela.INFORMACAO){
            botaoCadastra.setVisible(false);
            botaoCancelar.setVisible(false);
            botaoPesquisarCliente.setEnabled(false);
        } else {
            botaoCadastra.setEnabled(false);
            
        }

        botaoRemover.setVisible(false);
        botaoAdd.setVisible(false);
        tabelaCortinas.setEnabled(false);
        tabelaServicos.setEnabled(false);
        campoCodigo.setEnabled(false);         
        campoTamanho.setEnabled(false);
        botaoPesquisaItem.setEnabled(false);
    }

    private void setModelo(JTable tabela, String[] modelo, double[] porcentagemTamanhoColunas) {

        //Override o metodo isCellEditable para nao deixar editar as celulas da tabela.
        tabela.setModel(new javax.swing.table.DefaultTableModel(new Object[][]{}, modelo) {

            @Override
            public boolean isCellEditable(int row, int col) {
                return false;
            }
        });
        tabela.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

        this.porcentagemTamanhoColunas = porcentagemTamanhoColunas;

        redimensionarColunas(tabela);
    }

    private void redimensionarColunas(JTable tabela) {
        double t = scrollItens.getWidth();

        for(int i = 0; i < porcentagemTamanhoColunas.length; i++){
            tabela.getColumnModel().getColumn(i).setPreferredWidth((int) ((porcentagemTamanhoColunas[i] * t) / 100));
        }
    }

    public void setCliente(Cliente c) {
        //se ja foi adicionado cliente anteriormente...
        if(cliente != null){
            reiniciar();
        }
        botaoPesquisaItem.setEnabled(true);
        campoCodigo.setEnabled(true);
        campoTamanho.setEnabled(true);
        botaoCadastra.setEnabled(true);

        labelCliente.setText(c.getNome());
        
        this.cliente = c;
    }

    public void adicionar(Cortina c, double tamanho) {
        pedido.getCarrinhoCortinas().add(c, tamanho);
        DefaultTableModel modelo = (DefaultTableModel) tabelaCortinas.getModel();
        modelo.addRow(new Object[]{c.getCodigo(), c.getNome(), tamanho,
                    formatoDecimal.format(c.getValor())});
    }

    
    public void verificarBotaoRemover(JTable tabela) {
        if(tabela.getSelectedRow() != -1) {
            botaoRemover.setVisible(true);
        } else {
            botaoRemover.setVisible(false);
        }
    }

    protected Pedido gerarPedidio() {

        
        pedido.setCliente(cliente);
        String[] data = getDateTime().split("/");
        GregorianCalendar hoje = new GregorianCalendar(Integer.valueOf(data[2]),
                Integer.valueOf(data[1]), Integer.valueOf(data[0]));
        pedido.setDataEntrada(hoje);
        

        return pedido;
    }

    private String getDateTime() {
        DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
        Date date = new Date();
        return dateFormat.format(date);
    }

    protected final void preencher() {
        labelCliente.setText(pedido.getCliente().getNome());
        setTotal(pedido.total());

        
        DefaultTableModel modeloServicos = (DefaultTableModel) tabelaServicos.getModel();
        DefaultTableModel modeloProdutos = (DefaultTableModel) tabelaCortinas.getModel();

        for(int i = 0; i < pedido.getCarrinhoCortinas().getCortinas().size(); i++){
            Object[] dados = new Object[4];
            dados[0] = pedido.getCarrinhoCortinas().getCortinas().get(i).getCodigo();
            dados[1] = pedido.getCarrinhoCortinas().getCortinas().get(i).getNome();
            dados[2] = pedido.getCarrinhoCortinas().getQtde().get(i);
            dados[3] = pedido.getCarrinhoCortinas().getCortinas().get(i).getValor();
            modeloProdutos.addRow(dados);
        }
    }

    protected boolean existemDependencias() {
        boolean existemDependencias = false;

        if(total == 0){
            JOptionPane.showMessageDialog(this, "A venda está vazia");
            existemDependencias = true;
        }

        return existemDependencias;
    }

    protected void cadastrar() {
    }

    protected void alterar() {
    }

    public void setCodigo(int codigo) {
        campoCodigo.setText(String.valueOf(codigo));
        botaoAdd.setVisible(true);
        

        reiniciar();
    }
}
